package com.gxa.employment.controller;


import com.gxa.employment.common.Result;
import com.gxa.employment.entity.vo.FileVo;
import org.apache.commons.fileupload.FileItem;
import org.apache.commons.fileupload.FileItemFactory;
import org.apache.commons.fileupload.FileUploadException;
import org.apache.commons.fileupload.disk.DiskFileItemFactory;
import org.apache.commons.fileupload.servlet.ServletFileUpload;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

import javax.servlet.ServletContext;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.File;
import java.util.Iterator;
import java.util.List;
import java.util.UUID;

/*
上传图片，上传纸质照片
*/
/*@RestController
@RequestMapping("/img")*/
@RestController
@RequestMapping("/img")
public class UploadController {
    @Autowired
    ServletContext context;
    @PostMapping("/img")
    public Result img(HttpServletRequest request, HttpServletResponse response) {
        FileItemFactory factory = new DiskFileItemFactory();
// 文件上传处理器
        ServletFileUpload upload = new ServletFileUpload(factory);
// 解析请求信息
        List<FileItem> items = null;
        try {
            items = upload.parseRequest(request);
        } catch (FileUploadException e) {
            e.printStackTrace();
        }
// 对请求信息进行判断
        Iterator iter = items.iterator();
// 要给前端返回的文件名
        String fileName = null;
        while (iter.hasNext()) {
            FileItem item = (FileItem) iter.next();
// 信息为文件格式
            if (!item.isFormField()) {
                String tempName = item.getName();//获得上传图片的名称
//截图20250120142845.png
// uuid生成文件名
                fileName = UUID.randomUUID().toString().replaceAll("-", "");
// 获取后缀名(.png)
                String ext = tempName.substring(tempName.lastIndexOf("."));
                System.out.println(ext);
// 06cfdc8c2d444c19aa62ab5679afe9e9.png
                fileName = fileName + ext;
                String basePath =
                        context.getRealPath("/upload/images/");
// 生成File对象
                File file = new File(basePath, fileName);
                try {
// 将上传的二进制数据写入目标文件对象
                    item.write(file);
                } catch (Exception e) {
                    e.printStackTrace();
                }
            }
        }
        return Result.success(new FileVo("/upload/images/" + fileName));
    }
}